package com.xposed.openfire.smack.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xposed.openfire.smack.R;
import com.xposed.openfire.smack.entity.ChatRecord;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ChatRecordAdapter extends RecyclerView.Adapter<ChatRecordAdapter.ChatRecordViewHolder> implements View.OnClickListener {

    private Context mContext;
    private List<ChatRecord> chatRecords;

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public ChatRecordAdapter(Context mContext, List<ChatRecord> chatRecords) {
        this.mContext = mContext;
        this.chatRecords = chatRecords;
    }

    @NonNull
    @Override
    public ChatRecordViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.recycler_item_chat_record, viewGroup, (false));
        inflate.setOnClickListener(this);
        return new ChatRecordViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull final ChatRecordViewHolder viewHolder, int position) {
        viewHolder.tvName.setText(chatRecords.get(position).getName());
        viewHolder.tvLastMsg.setText(chatRecords.get(position).getLastMsgText());
        viewHolder.itemView.setTag(position);
    }

    @Override
    public int getItemCount() {
        return chatRecords.size();
    }

    /**
     * 加载数据
     */
    public void addData(List<ChatRecord> chatRecords) {
        this.chatRecords.clear();
        this.chatRecords.addAll(chatRecords);
        notifyDataSetChanged();
    }

    /**
     * 加载数据
     */
    public void addItem(ChatRecord chatRecord) {
        this.chatRecords.add(getItemCount(), chatRecord);
        notifyItemChanged(getItemCount());
    }

    @Override
    public void onClick(View v) {
        if (onItemClickListener != null)
            onItemClickListener.onItemClick(v, (int) v.getTag());
    }

    public interface OnItemClickListener {

        void onItemClick(View view, int position);
    }

    class ChatRecordViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_last_msg)
        TextView tvLastMsg;

        ChatRecordViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind((this), itemView);
        }
    }
}
